import 'package:eshi/app/CommonFunctions.dart';
import 'package:eshi/app/shi/data/HistoryConfig.dart';
import 'package:eshi/app/shi/data/Config.dart';
import 'package:eshi/app/shi/data/History.dart';
import 'package:eshi/app/shi/data/china_history.dart';
import 'package:eshi/app/shi/data/parse/IndentParser.dart';
import 'package:eshi/app/shi/data/parse/TxtPointParser.dart';

import 'parse/FileParser.dart';

/// tab文本方式的 历史
class TabTxtHistory extends History{
  //所有的文件和内容 
  static Map<String,String> _allTxt = {};
  
  static initItems() async {
     _allTxt = await FileParser.readDirFiles();
  }
  static Map<String,String> all({filter=true}) {
       final allTxt = _allTxt;
       if(filter){
          final dels = Config.historyDisableList;
          allTxt.removeWhere((name,data) => dels.contains(name)); 
       }
       return allTxt;
  }
  static Future<String> loadContent(name,[bool mustfromFile=false]) async{
      var data="";
      if(!mustfromFile && _allTxt.containsKey(name) && _allTxt[name]!.isNotEmpty ){
        data = _allTxt[name]!;
      }else{
        data = await FileParser.getTextContent(name);
        _allTxt[name] = data;
      }
      return data;
  }
  static Future<History> load(String name,[bool fromFile=false]) async{
      var data="";
      final r= RegExp(r'[\./]');
      var defaultPath = "";
      if(name.contains(r)){
        var a= name.split(r);
        name = a.removeAt(0);
        defaultPath = a.join("/");
      }
      if(name == "中国历史" && !_allTxt.containsKey(name)){
         return china_history();
      }
      data = await loadContent(name,fromFile);
      if(data.isEmpty) return china_history();
      return TabTxtHistory(data,name:name)
          ..defaultPath = defaultPath
          ..id = all().keys.toList().indexOf(name)+1;
  }

   static void update(String name, String doc,{marks}) {
      if(HistoryConfig.isReadOnly(name)) {
        msgErr("文档只读无法修改!");
        return;
      }
      var end="";
      if(marks!=null && marks.isNotEmpty){
        var rt="引用\n";
        marks.forEach((k,v){
            rt+=IndentParser.sp+k;
            rt+=IndentParser.sp*2 +v.join(",");
        });
        end = "$rt\n";
      }
      _allTxt[name] = "";
      FileParser.save("$name.txt",doc+end);
   }
  static Future<bool> remove(name) async{
    final file = FileParser.assetsFile("assets/txt/$name.txt");
    await file.delete();
    final rt= ! await file.exists();
    if(rt) _allTxt.remove(name);
    return rt;
  }
  TabTxtHistory(text,{String name=""}){
    this.name = name;
    TxtPointParser.parse(text,this,name:name);
    // initDataByTableText(text);
    // initDataByTableText(text,createPointBefore: (p){});
  }
 
}